package com.github.hgbit;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;


/**
 * ServletUtil.
 *
 * @author huangguan
 * @since 2019-03-13
 */
public class ServletUtil {

    /**
     * 获取客户端真实ip.
     *
     * @param request request
     * @return String
     */
    public static String getRemoteAddressHost(HttpServletRequest request) {
        String host = request.getHeader("X-Real-IP");
        if (StringUtils.isBlank(host) || "unknown".equalsIgnoreCase(host)) {
            host = request.getHeader("X-Forwarded-For");
        }

        if (StringUtils.isBlank(host) || "unknown".equalsIgnoreCase(host)) {
            host = request.getHeader("ip");
        }

        if (StringUtils.isBlank(host) || "unknown".equalsIgnoreCase(host)) {
            host = request.getRemoteAddr();
        }

        if (StringUtils.isNotBlank(host) && host.contains(",")) {
            host = host.substring(0, host.indexOf(",")).trim();
        }

        return host;
    }
}
